<template>
  <n-modal v-model:show="isVisible" title="添加客户订单" preset="dialog" @close="onClose" style="height: 600px;width: 700px">
    <n-form @submit.prevent="handleSubmit" label-width="120px" class="form-container" style="margin-left: 60px">
      <div class="form-row" style="margin-top: 20px">
        <n-form-item label="产品：" path="productId">
          <n-select
              v-model:value="form.storeCommodityId"
              style="width:250px"
              size="small"
              :options="storeCommodity"
              filterable
              @update:value="handleProductChange"
          />
        </n-form-item>
        <n-form-item label="数量：" path="quantity" style="margin-left: 20px" :feedback="inventoryFeedback">
          <n-input v-model:value="form.quantity" placeholder="请输入产品数量" style="width:250px" @update:value="handleQuantityChange"/>
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="金额：" path="price" style="width: 250px">
          <n-input v-model:value="form.price" placeholder="请输入订单金额" disabled/>
        </n-form-item>
        <n-form-item label="币种：" path="currency" style="margin-left: 20px;width: 250px">
          <n-select
              v-model:value="form.currencyId"
              style="width:250px"
              size="small"
              :options="currencies"
              filterable
          />
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="店铺：" path="shopId" style="width: 250px">
          <n-select
              v-model:value="form.shopId"
              style="width:250px"
              size="small"
              :options="shops"
              filterable
          >
          </n-select>
        </n-form-item>
        <n-form-item label="物流商：" path="logisticsProviderId" style="margin-left: 20px;width: 250px">
          <n-select
              v-model:value="form.logisticsProviderId"
              style="width:250px"
              size="small"
              :options="logisticsProviders"
              filterable
              @update:value="handleLogisticsProviderChange"
          >
          </n-select>
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="客户：" path="customerId" style="width: 250px">
          <n-select
              v-model:value="form.customerId"
              style="width:250px"
              size="small"
              :options="customers"
              filterable
          >
          </n-select>
        </n-form-item>
        <n-form-item label="客户电话：" path="customerPhone" style="margin-left: 20px;width: 250px">
          <n-input v-model:value="form.customerPhone" placeholder="请输入客户电话"/>
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="促销活动：" path="salePromotionId" style="width: 250px">
          <n-select
              v-model:value="form.salePromotionId"
              style="width:250px"
              size="small"
              :options="salePromotions"
              filterable
          >
          </n-select>
        </n-form-item>
        <n-form-item label="客户地址：" path="customerAddress" style="margin-left: 20px;width: 250px">
          <n-input v-model:value="form.customerAddress" placeholder="请输入客户地址"/>
        </n-form-item>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-row" style="margin-left: -65px">
        <n-form-item>
          <n-button type="primary" native-type="submit" @click="handleSubmit">提交</n-button>
        </n-form-item>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue';
import {useUserStore} from "@/store/index.js";
import api from '@/api/admin.js'
import {List} from "echarts";

const userStore = useUserStore()
const id = userStore.getId();
const inventory = ref(null);
const option = ref([
])
const currencies = ref([
])
function handleChange(value) {
}
const emit = defineEmits(['updatePage'])
const props = defineProps({
  show: {
    type: Boolean,
    required: true,
  },
  onClose: {
    type: Function,
    required: true,
  },
  option: {
    type: List,
    require: true
  },
  statuses: {
    type: Array,
    required: true
  },
  storeCommodity: {
    type: Array,
    required: true
  },
  shops: {
    type: Array,
    required: true
  },
  logisticsProviders: {
    type: Array,
    required: true
  },
  customers: {
    type: Array,
    required: true
  },
  salePromotions: {
    type: Array,
    required: true
  },
});

const isVisible = ref(props.show);
watch(() => props.show, (newVal) => {
  isVisible.value = newVal;
});

const form = ref({
  storeCommodityId: null,
  quantity: '',
  price: '',
	currencyId: '',
  currency: '',
  shopId: null,
  logisticsProviderId: null,
  logisticsProvider: '',
  customerId: null ,
  customerPhone: '' ,
  salePromotionId: null ,
  customerAddress: ''
});

const handleLogisticsProviderChange = (value) => {
  const selectedProvider = props.logisticsProviders.find(provider => provider.value === value);
  form.value.logisticsProvider = selectedProvider ? selectedProvider.label : '';
};


const queryCurrencyList = async () => {
	try {
		const res = await api.findAllCurrency()
		if(res.code === 200) {
			res.data.map((item)=>{
				currencies.value.push({
					label: item.nameBefore,
					value: item.id
				})
			})
		}
		else {
			$message.error(res.message)
		}
	} catch (err) {
    $message.error("获取货币列表信息失败！")
	}
}

const handleProductChange = (value) => {
  form.value.storeCommodityId = value;
  checkInventory();
};
const checkInventory = async () => {
  if (form.value.storeCommodityId) {
    await queryInventory();
  }
};
const queryInventory = async () => {
  try {
    const res = await api.findStoreCommodityById(
        {params: {storeCommodityId:form.value.storeCommodityId}}
    )
    if (res.code === 200) {
      inventory.value = res.data.quantity;
    } else {
      $message.error(res.message);
    }
  } catch (err) {
    $message.error("获取库存信息失败！");
  }
};
const inventoryFeedback = computed(() => {
  return inventory.value !== null ? `当前库存量：${inventory.value}` : '';
});
const handleSubmit = async () => {
  try {
    // 首先添加客户订单
    const customerOrderRes = await api.addCustomerOrder({
      ...form.value,
      adminId: id,
      status: "未发货"
    });

    if (customerOrderRes.code === 200) {
      emit("updatePage");
    } else {
      $message.error(customerOrderRes.message);
      return;
    }
    // 然后添加物流订单，确保包含 customer_order_id 字段
    const logisticsProviderOrderRes = await api.addLogisticsProviderOrder({
      ...form.value,
      id: "",
      customerOrderId: customerOrderRes.data.id, // 提供 customer_order_id
      orderType: "customer_order",
      logisticsChannels: "",
      price: 0,
      status: "未发货",
      createTime: customerOrderRes.createTime,
      startTime: "",
      endTime: "",
      name: form.value.logisticsProvider,
    });

    if (logisticsProviderOrderRes.code === 200) {
      emit("updatePage");
    } else {
      $message.error(logisticsProviderOrderRes.message);
    }
  } catch (err) {
    $message.error("添加失败！");
  } finally {
    clear();
    props.onClose();
  }
};

const clear = () => {
  form.value.storeCommodityId = null
  form.value.quantity = ""
  form.value.currencyId = ""
  form.value.shopId = null
  form.value.logisticsProviderId = null
  form.value.customerId = null
  form.value.customerPhone = ""
  form.value.salePromotionId = null
  form.value.customerAddress = ""
  form.value.price = ""
}
const handleQuantityChange = async (value) => {
	form.value.quantity = value;
	try {
		console.log(form.value)
		const res1 = await api.findStoreCommodityById({
      params: {
	      storeCommodityId: form.value.storeCommodityId
      }
    })
		const res = await api.findProduct({
			id: res1.data.productId
		});
		const cost = parseFloat(res.data.cost) || 0; // 如果转换失败，则默认为0
		const quantity = parseFloat(value) || 0; // 如果转换失败，则默认为0
		form.value.price = (cost * quantity * 1.05).toFixed(2);
	}
	catch (e) {
		$message.error(e);
	}
};
onMounted(()=>{
	queryCurrencyList()
})
</script>

<style scoped>
.form-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  position: relative;
}

.form-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.form-row > n-form-item {
  flex: 1;
}

.submit-row {
  justify-content: center;
  display: flex;
  width: 100%;
}
</style>
